var map = new AMap.Map('container', {
    resizeEnable: true,
    zoom: 11,
    zooms: [10,18],
    center: [121.475164, 31.228816],
    mapStyle: 'amap://styles/blue',
});
var maputil = {
    init : function (){
        map.on('zoomchange',this.showHide);
        this.infoWindow = new AMap.InfoWindow({
            offset: new AMap.Pixel(0, -32), //弹窗位置
            autoMove: true
        });
        let markers = this.staticmarkers;
        for (var i = 0; i < markers.length; i++) {
            let icon;
            let content;
            if (markers[i].type == 1){
                icon = this.icon1;
                content = '<div style="background-image: url(./images/mapImg/5.png);width: 228px;height: 158px;"></div>'
            }else if (markers[i].type == 2){
                icon = this.icon2;
                content = '<div style="background-image: url(./images/mapImg/4.png);width: 228px;height: 113px;"></div>'
            }else if (markers[i].type == 3){
                icon = this.icon3;
                content = '<div style="background-image: url(./images/mapImg/'+ markers[i].content+');width: 376px;height: 172px;"></div>'
            };
            var marker = new AMap.Marker({
                position: [markers[i].x,markers[i].y],
                map: map,
                icon: icon,
                title: markers[i].name
            });
            this.markersArray.push(marker);
            marker.content = content;
            marker.on('click', this.markerClick);
            if (markers[i].type == 1){
                var circle = new AMap.Circle({
                    center: [markers[i].x,markers[i].y],
                    map: map,
                    radius: 8000,
                    strokeColor: '#ffffff',
                    strokeWeight: 1,
                    fillColor: '#ff0000',
                    fillOpacity: 0.3
                });
                this.circlesArray.push(circle);
            };
        }
    },
    markerClick : function(e){
        maputil.infoWindow.setContent(e.target.content);
        maputil.infoWindow.open(map, e.target.getPosition());
    },
    showHide : function(){
        let zoom = map.getZoom();
         console.log(zoom)
         if (zoom < 11){
             console.log(maputil.markersArray)
            for (var i = 0; i < maputil.markersArray.length; i++){
                maputil.markersArray[i].hide();
            }
            for (var i = 0; i < maputil.circlesArray.length; i++){
                maputil.circlesArray[i].hide();
            }
         }else {
            for (var i = 0; i < maputil.markersArray.length; i++) {
                maputil.markersArray[i].show();
            }
            for (var i = 0; i < maputil.circlesArray.length; i++) {
                maputil.circlesArray[i].show();
            }
         }
    },
    //静态展示用
    staticmarkers:[
        {name:'南翔地铁站',type:1,x:121.323141, y:31.296952},
        {name:'维保人员',type:2,x:121.363141, y:31.256952},
        {name:'梅陇路基地',type:3,x:121.42448, y:31.151189,content:'meilong.svg'},
        {name:'陈太路基地',type:3,x:121.369595, y:31.317503,content:'chentai.svg'},
        {name:'龙阳路基地',type:3,x:121.567759, y:31.204692,content:'longyang.svg'},
    ],
    infoWindow: '',

    icon1 : new AMap.Icon({
        image: './images/mapImg/1.png',
        size: [24,25]
    }),
    icon2 : new AMap.Icon({
        image: './images/mapImg/2.png',
        size: [36,36]
    }),
    icon3 : new AMap.Icon({
        image: './images/mapImg/3.png',
        size: [30,30]
    }),

    markersArray : [],
    circlesArray : [],
    humanArray : [],
    staticArray: [],
    historyArray: [],
    dutyArray: [],
    faultShowTableTitle: ['当前处置人数','故障时间','负责人','故障地点','联系方式','故障内容'],
    historyShowTableTitle: ['故障时间','接修单位','故障路线','报修单位','故障地点','故障设备','故障内容'],
    teamShowTableTitle: ['抢修内容','负责人','专业','联系方式'],
    personTableTitle: ['所属班组','联系方式'],
    dutyPointTableTitle: ['分公司','专业','班组名称','电话'],

    //外部调用API
    //  redraw为是否重绘:1重绘2不重绘3隐藏;
    //  marktype图标类型，1设备和抢修队；2人员；3应急事件；4正线值守点
    __draw: function(redraw,mapMarkersArray,clickFunction){
        let markerList = [];
        //需要重绘时清除原有图标
        if(redraw == 1)
        {
            if(mapMarkersArray[0].markType == 1){
                this.removeCircles();
                this.removeHistory();
            }else if(mapMarkersArray[0].markType == 2){
                this.removeHuman();
            }else if(mapMarkersArray[0].markType == 3){
                this.removeStatic();
            }else if(mapMarkersArray[0].markType == 4){
                this.removeDuty();
            }
        }else if(redraw == 3){
            if(mapMarkersArray[0].markType == 1){
                this.hideCircles();
            }else if(mapMarkersArray[0].markType == 2){
                this.hideHuman();
            }else if(mapMarkersArray[0].markType == 3){
                this.hideStatic();
            }else if(mapMarkersArray[0].markType == 4){
                this.hideDuty();
            }
        }
        mapMarkersArray.forEach(function(val,index,arr) {
            let icon;
            let marker;
            let x = val.x || 121.414776+(Math.random()-0.5)/100;
            let y = val.y || 31.184571+(Math.random()-0.5)/100;
            let marktype = val.markType;
            if(marktype == 1) //绘制红色圆圈与告警图标
            {
                icon = this.icon1;
                marker = new AMap.Marker({
                    position: [x,y],
                    icon: icon,
                    title: val.name,
                    anchor: 'center'
                });
                
                let circle = new AMap.Circle({
                    center: [x,y],
                    radius: 4000,
                    strokeColor: '#ffffff',
                    strokeWeight: 1,
                    fillColor: '#ff0000',
                    fillOpacity: 0.3
                });
                map.add(circle);
                if(val.faultMarkType == 'new'){
                    this.circlesArray.push(marker)
                    this.circlesArray.push(circle)
                }else {
                    this.historyArray.push(marker)
                    this.historyArray.push(circle)
                }
            }else if(marktype == 2) //绘制人员图标
            {
                icon = this.icon2;
                marker = new AMap.Marker({
                    position: [x,y],
                    icon: icon,
                    title: name,
                    anchor: 'center'
                });
                this.humanArray.push(marker)
            }else if(marktype == 3) //绘制静态图标
            {
                icon = this.icon3;
                marker = new AMap.Marker({
                    position: [x,y],
                    icon: icon,
                    title: name,
                    anchor: 'center'
                });
                this.staticArray.push(marker)
            }else if(marktype == 4) //绘制正线值守点
            {
                icon = new AMap.Icon({
                    image: './images/mapImg/major/ico-'+ val.etcData.dutyBigPro +'.png',
                    size: [30,30]
                });
                marker = new AMap.Marker({
                    position: [x,y],
                    icon: icon,
                    title: name,
                    anchor: 'center'
                });
                this.dutyArray.push(marker)
            }
            //为marker添加自定义属性
            marker.id = val.id || '';
            marker.dataType = val.dataType || '';
            marker.etcData = val.etcData || {};
            marker.statusButton = val.statusButton;
            markerList.push(marker);

            map.add(marker);

            // 为标记添加一个点击事件，点击查询详情和人员信息
            AMap.Event.addListener(marker, 'click', function () {
                let windowInfo = {}
                if(clickFunction){
                    windowInfo = clickFunction(marker.id,marker.dataType,marker.etcData,marker.statusButton);
                }
                let infoWindow = maputil.createInfoWindow(windowInfo);
                infoWindow.open(map, marker.getPosition());
            });
        },this);
        return markerList;
    },
    //仅删除警报圆图标与告警图标
    removeCircles : function()
    {
        map.remove(this.circlesArray)
        //清除数组对象
        this.circlesArray.length = 0
    },
    //仅隐藏警报圆图标与告警图标
    hideCircles : function()
    {
        this.circlesArray.forEach(function(val,index,arr) {
            if(val.className == 'Overlay.Circle'){
                if(val.visible){
                    val.hide()
                }
            }else{
                if(val.getVisible()){
                    val.hide()
                }
            }
        })
    },
    //仅删除历史和已完成警报圆图标与告警图标
    removeHistory : function()
    {
        map.remove(this.historyArray)
        //清除数组对象
        this.historyArray.length = 0
    },

    //仅显示警报圆图标与告警图标
    showCircles : function()
    {
        this.circlesArray.forEach(function(val,index,arr) {
            if(val.className == 'Overlay.Circle'){
                if(!val.visible){
                    val.show()
                }
            }else{
                if(!val.getVisible()){
                    val.show()
                }
            }
        })
    },

    //仅删除人员图标
    removeHuman : function()
    {
        map.remove(this.humanArray)
        //清除数组对象
        this.humanArray.length = 0
    },
    //仅隐藏人员图标
    hideHuman : function()
    {
        this.humanArray.forEach(function(val,index,arr) {
            val.hide()
        })
    },

    //仅删除静态图标
    removeStatic : function()
    {
        map.remove(this.staticArray)
        //清除数组对象
        this.staticArray.length = 0
    },
    //仅隐藏静态图标
    hideStatic : function()
    {
        this.staticArray.forEach(function(val,index,arr) {
            val.hide()
        })
    },

    //仅删除值守点图标
    removeDuty : function()
    {
        map.remove(this.dutyArray)
        this.dutyArray.length = 0
    },

    //仅显示值守点图标
    showDuty : function()
    {
        this.dutyArray.forEach(function(val,index,arr){
            if(!val.getVisible()){
                val.show()
            }
        })
    },

    //仅隐藏值守点图标
    hideDuty : function()
    {
        this.dutyArray.forEach(function(val,index,arr){
            if(val.getVisible()){
                val.hide()
            }
        })
    },

    //隐藏所有图标
    hideAllShapes : function()
    {
        map.getAllOverlays().forEach(function(val,index,arr){
            val.hide()
        })
    },

    //删除所有图标
    removeAllShapes : function()
    {
        map.clearMap()
        //清除数组对象
        this.circlesArray.length = 0
        this.humanArray.length = 0
        this.staticArray.length = 0
    },

    //创建消息弹窗
    createInfoWindow : function (info) {
        let windowType = info.windowType;
        let showParam = info.showParam;
        let paramWithoutName;

        let baseDiv = document.createElement('div');
        baseDiv.className = 'process';
        let backgroundImg = document.createElement('img');
        let body = document.createElement('div');
        body.className = 'processText';
        let baseNameAndCloseImg = document.createElement('div');
        let baseName = document.createElement('h3');
        baseName.style = 'margin-top: 20px;'
        
        let showTable = document.createElement('table');
        showTable.style = 'margin-top: 50px;margin-left:30px;margin-right: 30px;table-layout:fixed;';
        if(windowType === 'teams' || windowType === 'person' || windowType === 'duty'){
            backgroundImg.src = "./images/mapImg/processShortRectangle.svg";
            baseName.innerText = showParam.name;
            paramWithoutName = JSON.parse(JSON.stringify(showParam))
            delete paramWithoutName.name;
        }else{
            backgroundImg.src = "./images/mapImg/red window.svg";
            backgroundImg.className += 'faultImg';
            baseName.innerText = '应急故障';
            body.className += ' faultDiv';
        }
        if(windowType === 'fault'){
            this.createTable(showParam,showTable,this.faultShowTableTitle);
        }else if (windowType === 'person'){
            this.createTable(paramWithoutName,showTable,this.personTableTitle);
        }else if (windowType === 'teams'){
            this.createTable(paramWithoutName,showTable,this.teamShowTableTitle);
        }else if (windowType === 'history'){
            console.log(showParam)
            this.createTable(showParam,showTable,this.historyShowTableTitle);
        }else if (windowType === 'complete'){
            this.createTable(showParam,showTable,this.faultShowTableTitle);
        }else if (windowType === 'duty'){
            this.createTable(paramWithoutName,showTable,this.dutyPointTableTitle);
        }

        if(windowType === 'history' && info.buttonType != undefined){
            let button = this.createFlagButton(info.buttonType);
            baseName.appendChild(button);
        }
        baseNameAndCloseImg.appendChild(baseName);

        body.appendChild(baseNameAndCloseImg);
        body.appendChild(showTable);
        baseDiv.appendChild(backgroundImg);
        baseDiv.appendChild(body);

        let window = new AMap.InfoWindow({
            isCustom: true,  //使用自定义窗体
            content: baseDiv,
            offset: new AMap.Pixel(190, -20)
        });

        return window;
    },

    loadEmergency: function (){
        let markers = JSON.parse(JSON.stringify(this.staticmarkers))
        for (var i = 2; i < markers.length; i++) {
            let icon = this.icon3;
            let content = '<div style="background-image: url(./img/'+ markers[i].content+');width: 376px;height: 172px;"></div>'

            let marker = new AMap.Marker({
                position: [markers[i].x,markers[i].y],
                map: map,
                icon: icon,
                title: markers[i].name
            });
            marker.on('click', function () {
                let window = new AMap.InfoWindow({
                    isCustom: true,  //使用自定义窗体
                    content: content,
                    offset: new AMap.Pixel(190, -20)
                });
                window.open(map, marker.getPosition());
            });
            
            if (markers[i].type == 1){
                var circle = new AMap.Circle({
                    center: [markers[i].x,markers[i].y],
                    map: map,
                    radius: 8000,
                    strokeColor: '#ffffff',
                    strokeWeight: 1,
                    fillColor: '#ff0000',
                    fillOpacity: 0.3
                });
                this.circlesArray.push(circle);
            };
        }
    },

    //创建弹窗中的table表
    createTable: function (showParam, showTable, tableTitle) {
        let content;
        let paramKeys = Object.keys(showParam);
        let title = JSON.parse(JSON.stringify(tableTitle))
        if(title[title.length-1].indexOf("内容") != -1){
            let valueText = showParam[paramKeys[paramKeys.length - 1]];
            content = document.createElement('tr'); 
            let name = document.createElement('td');
            let value = document.createElement('td');
            name.vAlign = 'top';
            value.vAlign = 'top';
            value.setAttribute('valueText',valueText);
            value.onmousemove = this.mouseOnShowContent;
            value.onmouseout = this.mouseOutHideContent;
            name.innerHTML = title[title.length-1];
            value.innerHTML = valueText.length > 60 ? valueText.slice(0,57) + '...' : valueText;
            value.colSpan="3";
            content.appendChild(name);
            content.appendChild(value);
            title.length -= 1;
        }
        let lineNum = parseInt((paramKeys.length + 1)/2);
        for (let i = 0; i < lineNum; i++){
            let line = document.createElement('tr'); 
            let tdList = [document.createElement('td'),document.createElement('td'),document.createElement('td'),document.createElement('td')]
            if(i === 0){
                tdList[0].width = '120';
                tdList[1].width = '100';
                tdList[2].width = '100';
                tdList[3].width = '150';
            }
            for(let j = 0; j < 2; j++){
                if(title[2*i+j]){
                    tdList[j*2].innerHTML = title[2*i+j]+'：';
                    let showText = showParam[paramKeys[2*i+j]] || '--';
                    if(title[2*i+j] == '故障设备' && showText.length >= 10){
                        tdList[j*2+1].title = showText;
                        tdList[j*2+1].innerHTML = showText.slice(0,9) + '...';
                    }else{
                        tdList[j*2+1].innerHTML = showText;
                    }
                }
            }
            for(let index in tdList){
                tdList[index].vAlign = 'top';
                line.appendChild(tdList[index]);
            }
            showTable.appendChild(line);
        }
        if(content){
            showTable.appendChild(content);
        }
    },

    // 创建历史数据的标志
    createFlagButton : function (type) {
        let button = document.createElement('button');
        button.innerText = type;
        if(type == '新报修'){
            button.style = 'background-color:rgb(255,191,0);color:white;';
        }else if (type == '延迟修复'){
            button.style = 'background-color:rgb(237,125,49);color:white;';
        }else if (type == '在处理'){
            button.style = 'background-color:rgb(68,114,199);color:white;';
        }else if (type == '已修复'){
            button.style = 'background-color:rgb(0,175,80);color:white;';
        }else if (type == '已完结'){
            button.style = 'background-color:rgb(58,86,33);color:white;';
        }
        button.style = button.style.cssText +'float:right;margin-right: 20px;padding: 5px 10px;border:0px';
        return button;
    },

    // 当鼠标移入维修内容行且内容长度超过60时，弹出窗口显示内容
    mouseOnShowContent: function (){
        let contentText = event.currentTarget.innerHTML;
        if(contentText.length >= 60){
            let showDiv = document.getElementById('showDiv');
            showDiv.style.left = event.clientX + 20 + 'px';
            showDiv.style.top = event.clientY + 10 + 'px';
            showDiv.style.display = 'block';
            showDiv.innerHTML = event.currentTarget.getAttribute('valueText');
        }
    },
    
    //当鼠标移出维修内容行时，关闭窗口
    mouseOutHideContent : function (){
        let showDiv = document.getElementById('showDiv');
        showDiv.style.display = 'none';
        showDiv.innerHTML = '';
    },

    //外部调用初始化
    __init: function() {
        console.log('初始化地图')
        map.on('click', this.closeInfoWindow);
    },

    //关闭信息窗体
    closeInfoWindow: function () {
        map.clearInfoWindow();
    }
}
// maputil.init();